﻿#include"Widget.h"
int Widget::getCurrentIndex() {
    return currentIndex;
}
//增加页面
void Widget::addPage(IMAGE* page)
{
    pages.emplace_back(page);
    buttons.push_back({});
    textBoxs.push_back({});
    outtextxys.push_back({});
    tables.push_back({});
}
//增加按钮
void Widget::addButton(int index, Button* button)
{
    if (index >= 0 && index < buttons.size())
    {
        buttons[index].emplace_back(button);
    }
}
//增加文本框
void Widget::addTextBox(int index, TextBox* textBox)
{
    if (index >= 0 && index < textBoxs.size())
    {
        textBoxs[index].emplace_back(textBox);
    }
}
//添加标签
void Widget::addouttextxy(int index, OutTextXY* outtextxy) {
    if (index >= 0 && index < outtextxys.size())
    {
        outtextxys[index].emplace_back(outtextxy);
    }
}
//添加表格
void Widget::addTable(int index, TableWidget* button)
{
    if (index >= 0 && index < tables.size())
    {
        tables[index].emplace_back(button);
    }
}
//修改标签
void Widget::transformOuttextxy(int page, int index1, wstring content) {
    outtextxys[page][index1]->setText(content);
    //outtextxys[page].erase(outtextxys[page].begin() + index1);
    //outtextxys[page].insert(outtextxys[page].begin() + index1, outtextxy);
}
//修改按钮
void Widget::transformButton(int page, int index1, Button* button) {
    buttons[page].erase(buttons[page].begin() + index1);
    buttons[page].insert(buttons[page].begin() + index1, button);
}
void Widget::setCurrentIndex(int index)
{
    if (index >= 0 && index < pages.size())
    {
        currentIndex = index;
    }
}
//鼠标点击
void Widget::mouseClick(int mouseX, int mouseY)
{
    bool finishClick = false;
    if (currentIndex >= 0 && currentIndex < buttons.size())
    {
        for (Button* button : buttons[currentIndex])
        {
            if (button->checkClick(mouseX, mouseY))
            {
                finishClick = true;
                break;
            }
        }
    }
    if (!finishClick && currentIndex >= 0 && currentIndex < textBoxs.size())
    {
        for (auto textbox : textBoxs[currentIndex])
        {
            if (textbox->checkClick(mouseX, mouseY)) {
                finishClick = true;
                break;
            }
        }
    }
    if (!finishClick && currentIndex >= 0 && currentIndex < tables.size())
    {
        for (TableWidget* table : tables[currentIndex])
        {
            auto selectRow = table->handleMouseClick(mouseX, mouseY);
            rowPosition = selectRow.first;
            bool flag_selected = selectRow.second;
            //finishClick = flag_selected;
            if (rowPosition > 0 && currentIndex == 5) { //如果被选中了，把线画出来
                if (processor.FlightLines.size() == 0) {
                    auto [table5_0x, table5_0y] = extractNumbers(tables[5][0]->getRowColData(rowPosition, 0));
                    plotView.resetView(table5_0x, table5_0y, 8);
                    continue;
                }
                if (plotView.changeRowShow(rowPosition)) {
                    plotView.fitToPoints(rowPosition);
                }
            }
        }
    }
    /*
    if (!finishClick && currentIndex >= 0 && currentIndex < tables.size())
    {
        for (TableWidget* table : tables[currentIndex])
        {
            table->handleMouseDown(mouseX,mouseY);
        }
    }*/
    if (currentIndex == 5) {
        plotView.mouseClick(mouseX, mouseY);
    }
}
//数轮滚动
void Widget::mouseWheel(int mouseX, int mouseY, int wheel)
{
    if (currentIndex == 5) {
        plotView.mouseWheel(mouseX, mouseY, wheel);
    }
    if (currentIndex >= 0 && currentIndex < tables.size())
    {
        for (TableWidget* table : tables[currentIndex])
        {
            table->scroll(mouseX, mouseY, wheel);
        }
    }
}
//鼠标移动
void Widget::mouseMove(int mouseX, int mouseY)
{
    //cout<<"鼠标所在位置:" << mouseX << " " << mouseY << "\n";
    if (currentIndex == 5) {
        plotView.mouseMove(mouseX, mouseY);
    }
    if (currentIndex >= 0 && currentIndex < buttons.size())
    {
        for (Button* button : buttons[currentIndex])
        {
            button->checkMouseOver(mouseX, mouseY);
        }
    }
}
//文本框的输入
void Widget::keyInput(wchar_t ch)
{
    if (currentIndex >= 0 && currentIndex < textBoxs.size())
    {
        for (auto textbox : textBoxs[currentIndex])
        {
            if (textbox->getSelect())
            {
                if (textbox->keyInput(ch)) break;   //输入信息处理成功就结束
            }
        }
    }
}
//文本框的输入
void Widget::handleKeyEvent(int vkCode)
{
    //if (ctrlPressed && vPressed && currentIndex >= 0 && currentIndex < textBoxs.size()) {
    //    for (auto textbox : textBoxs[currentIndex])
    //    {
    //        if (textbox->getSelect())
    //        {
    //            // 先尝试获取文件路径
    //            wstring clipboardContent = GetFilePathsFromClipboard();
    //            if (clipboardContent.empty()) {
    //                // 再尝试获取普通文本
    //                clipboardContent = GetClipboardTextW();
    //            }
    //            if (!clipboardContent.empty()) {
    //                textbox->setText(clipboardContent);
    //            }
    //            break;
    //        }
    //    }

    //}
    //else 
    if (currentIndex >= 0 && currentIndex < textBoxs.size())
    {
        for (auto textbox : textBoxs[currentIndex])
        {
            if (textbox->getSelect())
            {
                if (textbox->handleKeyEvent(vkCode)) break;   //输入信息处理成功就结束
            }
        }
    }



}
//绘制画面
void Widget::draw()
{
    if (currentIndex >= 0 && currentIndex < pages.size())
    {
        putimage(0, 0, pages[currentIndex]);

        if (currentIndex >= 0 && currentIndex < textBoxs.size())
        {
            for (auto textbox : textBoxs[currentIndex])
            {
                if (textbox->getSelect())
                {
                    textbox->updateCursor();
                }
                textbox->draw();
            }
        }

        if (currentIndex >= 0 && currentIndex < buttons.size())
        {
            for (Button* button : buttons[currentIndex])
            {
                button->draw();
            }
        }

        if (currentIndex >= 0 && currentIndex < outtextxys.size())
        {
            for (OutTextXY* outtextxy : outtextxys[currentIndex])
            {
                outtextxy->draw();
            }
        }

        if (currentIndex >= 0 && currentIndex < tables.size())
        {
            for (TableWidget* table : tables[currentIndex])
            {
                table->draw();
            }
        }

        if (currentIndex == 5) {
            plotView.drawCoordinateSystem();
            plotView.drawAllData();
            // 面板背景
            //setfillcolor(WHITE);
            //fillrectangle(0, 0, 200*rpx, 870*rpy);
            //settextcolor(RGB(64, 64, 64));

            // 显示UI信息
            settextcolor(WHITE);
            settextstyle(14, 0, _T("宋体"));
            double centerX, centerY;
            plotView.getViewCenter(centerX, centerY);
            TCHAR info[100];
            _stprintf_s(info, _T("缩放: %.2f%%  视图中心: (%.2f, %.2f)"),
                plotView.getZoom() * 100, centerX, centerY);
            outtextxy(248 * rpx + 10, 10 * rpy, info);

            setlinestyle(PS_SOLID, 1);
        }
    }
}

void Widget::transformWindow() {
    if (width != screenWidth * 2) {
        // 重置为大窗口尺寸
        width = screenWidth * 2;
        height = screenHeight * 2;
        rpx = 1.0; // 缩放比例恢复为1
        rpy = 1.0;
    }
    else {
        // 切换为小窗口尺寸（屏幕分辨率的1/2）
        width = screenWidth;
        height = screenHeight;
        rpx = 0.5; // 缩放比例为0.5
        rpy = 0.5;
    }
    if (width != screenWidth * 2) {
        buttons[1][4]->setText(L"全屏");
    }
    else {
        buttons[1][4]->setText(L"小窗口");
    }
    close();
    initgraph(width, height);
    pages.clear();
    initPage();
    for (auto& button : buttons) {
        for (auto& Abutton : button) {
            Abutton->updateSecond();
        }
    }
    for (auto& outtextxy : outtextxys) {
        for (auto& Aouttextxy : outtextxy) {
            Aouttextxy->updateSecond();
        }
    }
    for (auto& textbox : textBoxs) {
        for (auto& Atextbox : textbox) {
            Atextbox->updateSecond();
        }
    }
    for (auto& table : tables) {
        for (auto& Atable : table) {
            Atable->updateSecond();
        }
    }
    //设置地图  start
    plotView = PlotView(248 * rpx,  // 左侧面板宽度
        width,   // 屏幕宽度
        height);   // 屏幕高度
    // // 清空所有页面和元素
    //pages.clear();
    //buttons.clear();
    //textBoxs.clear();
    //outtextxys.clear();
    //tables.clear();
    ////重新初始化界面
    //init();
    need_to_update_table5 = true;

}

Widget::Widget(int width, int height)
    :width(width), height(height), currentIndex(-1), screenWidth(width), screenHeight(height), plotView(100, width, height), cs(0),
    need_to_update_table2(true), need_to_update_table5(true), rowPosition(-1),
    isdirectinput(false), ctrlPressed(false)
{
    rpx = 0.5, rpy = 0.5;

}
Widget::~Widget() {}



//使用说明界面内容
void Widget::initContentPage0() {
    //设置按钮 start
    Button* button0_1 = new Button(width - 65, 0, 65, 35, L"返回上一页", [&]() {
        setCurrentIndex(1);
        });
    addButton(0, button0_1);
    //设置按钮 end


    //设置文字 start
    OutTextXY* out0_0 = new OutTextXY(80, 50, L"传入的txt文件格式说明（若csv文件则用空格隔开）：", 20);
    out0_0->setSecondPosition(160, 100, 33);
    addouttextxy(0, out0_0);
    OutTextXY* out0_1 = new OutTextXY(105, 75, L"第一行输入n和m，二者用空格隔开", 20);
    out0_1->setSecondPosition(210, 150, 33);
    addouttextxy(0, out0_1);

    OutTextXY* out0_2 = new OutTextXY(105, 102, L"接下来的n行中，每行给出x1 y1 x2 y2（代表一条飞行线的两个端点，空格隔开）", 20);
    out0_2->setSecondPosition(210, 205, 33);
    addouttextxy(0, out0_2);

    OutTextXY* out0_3 = new OutTextXY(105, 122, L"接下来m行中，每行给出x y（代表查询点的坐标，空格隔开）", 20);
    out0_3->setSecondPosition(210, 255, 33);
    addouttextxy(0, out0_3);

    OutTextXY* out0_4 = new OutTextXY(105, 172, L"传入的数据将自动保留到小数点后至多两位", 20);
    out0_4->setSecondPosition(210, 345, 33);
    addouttextxy(0, out0_4);
    //设置文字 end
}
//主界面内容(进程序第一个界面)
void Widget::initContentPage1() {
    //设置按钮 start
    Button* button1_1 = new Button(265, 155, 165, 27, L"运行", [&]() {
        wstring gettext = textBoxs[1][0]->getText();
        int Get_Num = processor.readDataFile(gettext);
        if (0 == Get_Num) {
            MessageBox(GetHWnd(), L"无法打开文件!", L"警告", MB_ICONWARNING | MB_OK);
        }
        else if (-1 == Get_Num) {
            MessageBox(GetHWnd(), L"请传入.txt文件或.csv文件！", L"警告", MB_ICONWARNING | MB_OK);
        }
        else if (-2 == Get_Num) {
            wstring errorMessage = wstring(L"第") + to_wstring(processor.getCurrentLine()) + wstring(L"行数据为空");
            MessageBox(GetHWnd(), errorMessage.c_str(), L"警告", MB_ICONWARNING | MB_OK);
        }
        else if (-3 == Get_Num) {
            wstring errorMessage = wstring(L"第") + to_wstring(processor.getCurrentLine()) + wstring(L"行数据数量不足");
            MessageBox(GetHWnd(), errorMessage.c_str(), L"警告", MB_ICONWARNING | MB_OK);
        }
        else if (-4 == Get_Num) {
            wstring errorMessage = wstring(L"第") + to_wstring(processor.getCurrentLine()) + wstring(L"行数据数量过多");
            MessageBox(GetHWnd(), errorMessage.c_str(), L"警告", MB_ICONWARNING | MB_OK);
        }
        else if (-5 == Get_Num) {
            wstring errorMessage = wstring(L"第") + to_wstring(processor.getCurrentLine()) + wstring(L"行数据不合法");
            MessageBox(GetHWnd(), errorMessage.c_str(), L"警告", MB_ICONWARNING | MB_OK);
        }
        else if (-6 == Get_Num) {
            wstring errorMessage = wstring(L"第") + to_wstring(processor.getCurrentLine()) + wstring(L" 行数据请在[0,65535]之间");
            MessageBox(GetHWnd(), errorMessage.c_str(), L"警告", MB_ICONWARNING | MB_OK);
        }
        else if (-7 == Get_Num) {
            MessageBox(GetHWnd(), L"第一行预计数量与实际数量不符", L"警告", MB_ICONWARNING | MB_OK);
        }
        else if (-404 == Get_Num) {
            MessageBox(GetHWnd(), L"遇到未知错误！", L"警告", MB_ICONWARNING | MB_OK);
        }

        else {
            setCurrentIndex(2);
            isdirectinput = false;
            need_to_update_table5 = true;
            //查询点情况
            vector<vector<wstring>>newdata1;
            processor.getQueryPointDataReference(newdata1);
            tables[2][0]->setData(newdata1);

            /*添加/删除 飞行线界面*/
            vector<vector<wstring>>newdata2;
            processor.getFlightDataReference(newdata2);
            tables[3][0]->setData(newdata2);
            tables[4][0]->setData(newdata2);

        }
        });
    addButton(1, button1_1);

    Button* button1_2 = new Button(265, 190, 165, 27, L"不用文件，直接输入", [&]() {
        isdirectinput = true;
        need_to_update_table5 = true;
        setCurrentIndex(6);
        });
    addButton(1, button1_2);

    Button* button1_3 = new Button(530, 117, 35, 19, L"清空", [&]() {
        textBoxs[1][0]->clear();
        });
    addButton(1, button1_3);

    Button* button1_4 = new Button(width - 65, 35, 65, 35, L"使用说明", [&]() {
        setCurrentIndex(0);
        return 0;
        });
    addButton(1, button1_4);

    Button* button1_5 = new Button(width - 65, 0, 65, 35, L"全屏", [&]() {
        transformWindow(); // 新增重新初始化函数
        });
    addButton(1, button1_5);

    Button* button1_6 = new Button(570, 117, 100, 19, L"保存为默认路径", [&]() {
        //usedatapath ;
        wstring fileName = L"usedefaultfilepath.txt";
        filesystem::path filePath = usedatapath / fileName;
        wstring gettext = textBoxs[1][0]->getText();
        // 打开文件进行写入
        wofstream outFile(filePath, ios::out);
        outFile.imbue(locale("chs"));

        if (outFile.is_open()) {
            outFile << gettext << std::endl;
            outFile.close();
            MessageBox(GetHWnd(), L"已保存为默认路径!", L"成功", MB_OK);
        }
        else {
            MessageBox(GetHWnd(), L"无法写入文件!", L"警告", MB_ICONWARNING | MB_OK);
        }
        });
    addButton(1, button1_6);
    //设置按钮 end

    //设置文字 start
    OutTextXY* out1_1 = new OutTextXY(145, 119, L"文件路径:", 18);
    out1_1->setSecondPosition(290, 238, 32);
    addouttextxy(1, out1_1);

    OutTextXY* out1_2 = new OutTextXY(235, 72, L"⽆⼈机最近⻜⾏线查询系统", 27);
    out1_2->setSecondPosition(470, 145, 45);
    addouttextxy(1, out1_2);

    OutTextXY* out1_3 = new OutTextXY(235, 230, L"tips: 可 ctrl+c 直接复制文件，然后 ctrl+v 粘贴", 17);
    addouttextxy(1, out1_3);



    //设置文字 end


    //设置文本输入框 start
        //在界面1创建文本框1        输入文件路径
    TextBox* textbox1_1 = new TextBox(200, 117, 320, 21, 50);
    textbox1_1->setFinalCallback([button1_1]() {
        button1_1->useOnClick();
        });
    textbox1_1->setDefaultText(L"请输入txt文件/csv文件的文件路径", 24 * rpx);
    addTextBox(1, textbox1_1);
    wstring fileName = L"usedefaultfilepath.txt";
    filesystem::path filePath = usedatapath / fileName;
    std::wifstream file(filePath);
    file.imbue(std::locale("chs"));
    if (file.is_open()) {
        std::wstring line;
        getline(file, line);
        textBoxs[1][0]->setText(line);
        file.close();
    }
    else {
        MessageBox(GetHWnd(), L"获取默认文件路径失败", L"失败", MB_ICONWARNING);
    }



    //设置文本输入框 end

}
//运行界面 内容
void Widget::initContentPage2() {
    //设置按钮 start
    {
        Button* button2_1 = new Button(width - 65, 0, 65, 35, L"返回上一页", [&]() {
            if (!isdirectinput) {
                processor.initDataStructures(0, 0);
                setCurrentIndex(1);
            }
            else {
                setCurrentIndex(7);
            }
            });
        addButton(2, button2_1);
        Button* button2_2 = new Button(width - 135, 90, 75, 35, L"添加飞行线", [&]() {
            setCurrentIndex(3);

            wstring flight_num = to_wstring(processor.FlightLines.size());
 
            transformOuttextxy(3, 5, L"当前飞行线数量: " + flight_num);

            });
        addButton(2, button2_2);

        Button* button2_3 = new Button(width - 135, 135, 75, 35, L"删除飞行线", [&]() {
            setCurrentIndex(4);

            wstring flight_num = to_wstring(processor.FlightLines.size());
            //OutTextXY* out4_2 = new OutTextXY(1070 * rpx, 120 * rpy, L"当前飞行线数量: " + flight_num, 18);
            //out4_2->setSecondPosition(535, 60, 32);
            transformOuttextxy(4, 0, L"当前飞行线数量: " + flight_num);

            });
        addButton(2, button2_3);

        Button* button2_4 = new Button(width - 135, 180, 75, 35, L"绘制图像", [&]() {
            if (need_to_update_table5) {
                vector<vector<wstring>>newdata1;
                processor.getQueryPointData_PointReference(newdata1);
                tables[5][0]->setData(newdata1);
                tables[5][0]->clearSelectedRows();

                plotView.clearAllData();
                for (int i = 0; i < processor.FlightLines.size(); ++i) {
                    plotView.addLineSegment(processor.FlightLines[i].x1, processor.FlightLines[i].y1, processor.FlightLines[i].x2, processor.FlightLines[i].y2, processor.FlightLines[i].id, true, to_wstring(processor.FlightLines[i].id), BLACK, 2);  //RGB(0, 190, 255), 2);to_wstring(processor.FlightLines[i].id)
                }
                for (int i = 0; i < processor.QueryPoints.size(); ++i) {
                    plotView.addDataPoint(processor.QueryPoints[i].x, processor.QueryPoints[i].y, tables[5][0]->getRowColData(i + 1, 0), RGB(255, 0, 0), RGB(255, 0, 250));
                }

                for (int i = 0; i < processor.QueryPoints.size(); ++i) {
                    if (processor.FlightLines.size() == 0 || processor.QueryPoints.size() == 0) break;
                    wstring id_wstring = tables[2][0]->getRowColData(i + 1, 1); //最近飞行线的id
                    int id_int = stoi(id_wstring);
                    int lineIndex = processor.findFlightLineIndex(id_int);
                    if (lineIndex == -1) {
                        MessageBox(GetHWnd(), L"查找最近飞行线出错!", L"警告", MB_ICONWARNING | MB_OK);
                        return;  // 跳过当前查询点
                    }
                    double min_distance = stod(tables[2][0]->getRowColData(i + 1, 2));  //点到最近飞行线的距离
                    auto footPoint = processor.findClosestPointOnSegment(processor.QueryPoints[i].x, processor.QueryPoints[i].y, 
                        processor.FlightLines[lineIndex].x1,  //获取垂足的坐标
                        processor.FlightLines[lineIndex].y1,
                        processor.FlightLines[lineIndex].x2,
                        processor.FlightLines[lineIndex].y2);

                    double footX = footPoint.first;
                    double footY = footPoint.second;
                    // 添加临时图形并关联当前行号
                    plotView.addDistanceGraphic(i, processor.QueryPoints[i].x, processor.QueryPoints[i].y, footX, footY, false, L"", to_wstring(min_distance));
                }


                need_to_update_table5 = false;
            }
            else setCurrentIndex(5);
            });
        addButton(2, button2_4);
    }
    //设置按钮 end

    //设置表格 start
        //查看答案
    TableWidget* table2_1 = new TableWidget(40, 40, 450, 330, 12, false, 0.5);
    addTable(2, table2_1);
    //设置表格 end

}
//添加飞行线界面内容
void Widget::initContentPage3() {
    //设置按钮 starts
    Button* button3_1 = new Button(width - 65, 0, 65, 35, L"返回上一页", [&]() {
        setCurrentIndex(2);
        });
    addButton(3, button3_1);

    Button* button3_2 = new Button(575, 245, 65, 33, L"添加", [&]() {
        wstring inputs[4] = {
        textBoxs[3][0]->getText(),
        textBoxs[3][1]->getText(),
        textBoxs[3][2]->getText(),
        textBoxs[3][3]->getText()
        };
        if (!inputs[0].empty() && !inputs[1].empty() && !inputs[2].empty() && !inputs[3].empty()) {
            // 输入验证
            int coords[4]; bool flag_isNonNegative = true;
            for (int i = 0; i < 4; ++i) {
                // 预处理：移除空格
                inputs[i].erase(std::remove(inputs[i].begin(), inputs[i].end(), ' '), inputs[i].end());
                // 严格数字验证
                bool isNumeric = std::all_of(inputs[i].begin(), inputs[i].end(),
                    [](wchar_t c) { return iswdigit(c); });
                if (!isNumeric) {
                    flag_isNonNegative = false;
                    textBoxs[3][i]->clear();
                    continue;
                }

                // 转换数字
                coords[i] = std::stoi(inputs[i]);
            }
            if (!flag_isNonNegative) {
                MessageBox(GetHWnd(), L"错误：输入数据存在错误信息", L"输入错误", MB_ICONERROR);
            }
            else {
                vector<wstring>arow(3);
                arow[0] = to_wstring(processor.getBianHao() );
                arow[1] = L"(" + inputs[0] + L"," + inputs[1] + L")";
                arow[2] = L"(" + inputs[2] + L"," + inputs[3] + L")";
                processor.addFlightLine(coords[0], coords[1], coords[2], coords[3]);
                //查询点情况
                vector<vector<wstring>>newdata1;
                processor.getQueryPointDataReference(newdata1);
                tables[2][0]->setData(newdata1);
                tables[3][0]->addRow(arow);
                tables[4][0]->addRow(arow);
                wstring flight_num = to_wstring(processor.FlightLines.size());
                transformOuttextxy(3, 5, L"当前飞行线数量: " + flight_num);
                transformOuttextxy(4, 0, L"当前飞行线数量: " + flight_num);
                textBoxs[3][0]->clear();
                textBoxs[3][1]->clear();
                textBoxs[3][2]->clear();
                textBoxs[3][3]->clear();
            }
        }

        need_to_update_table5 = true;
        });
    addButton(3, button3_2);

    //设置按钮 end


    //设置文字 start
    {
        //端点1 x坐标
        OutTextXY* out3_1 = new OutTextXY(535, 113, L"端点1  x坐标 :", 18);
        out3_1->setSecondPosition(1070, 226, 28);
        addouttextxy(3, out3_1);
        //端点1 y坐标
        OutTextXY* out3_2 = new OutTextXY(535, 143, L"端点1  y坐标 :", 18);
        out3_2->setSecondPosition(1070, 286, 28);
        addouttextxy(3, out3_2);
        //端点2 x坐标                       
        OutTextXY* out3_3 = new OutTextXY(535, 173, L"端点2  x坐标 :", 18);
        out3_3->setSecondPosition(1070, 346, 28);
        addouttextxy(3, out3_3);
        //端点2 y坐标                       
        OutTextXY* out3_4 = new OutTextXY(535, 203, L"端点2  y坐标 :", 18);
        out3_4->setSecondPosition(1070, 406, 28);
        addouttextxy(3, out3_4);
        //提示数量
        OutTextXY* out3_5 = new OutTextXY(535, 80, L"请输入飞行线端点坐标", 20);
        out3_5->setSecondPosition(1070, 160, 30);
        addouttextxy(3, out3_5);
        //飞行线数量
        OutTextXY* out3_6 = new OutTextXY(535, 60, L"当前飞行线数量: ", 18);
        out3_6->setSecondPosition(1070, 120, 32);
        addouttextxy(3, out3_6);
    }
    //设置文字 end


    //设置文本输入框 start
    {
        TextBox* textbox3_1 = new TextBox(615, 112, 65, 22, 8);//  端点1 X
        TextBox* textbox3_2 = new TextBox(615, 142, 65, 22, 8);//  端点1 Y
        TextBox* textbox3_3 = new TextBox(615, 172, 65, 22, 8);//  端点2 X
        TextBox* textbox3_4 = new TextBox(615, 202, 65, 22, 8);//  端点2 Y
        textbox3_1->setNextField(textbox3_2);
        textbox3_2->setNextField(textbox3_3);
        textbox3_3->setNextField(textbox3_4);
        textbox3_4->setNextField(textbox3_1);
        textbox3_4->setFinalCallback([button3_2]() {
            button3_2->useOnClick();
            });
        addTextBox(3, textbox3_1);
        addTextBox(3, textbox3_2);
        addTextBox(3, textbox3_3);
        addTextBox(3, textbox3_4);
    }
    //设置文本输入框 end


    //设置表格 start
    {
        //添加飞行线界面
        TableWidget* table3_1 = new TableWidget(40, 40, 450, 330, 12, false, 0.5);
        addTable(3, table3_1);
    }
    //设置表格 end
}
//删除飞行线界面内容  
void Widget::initContentPage4() {
    //设置按钮 start
    {
        Button* button4_1 = new Button(width - 65, 0, 65, 35, L"返回上一页", [&]() {
            setCurrentIndex(2);
            });
        addButton(4, button4_1);
        Button* button4_2 = new Button(575, 245, 65, 33, L"删除", [&]() {
                vector<int>selectedrows;
                tables[4][0]->getSelectedRows(selectedrows);
                int len = selectedrows.size();
                vector<pair<int,int>>selectidsandposition(len);
                //第一个来存线段的编号，然后第二个来存所在位置
                for (int i = 0; i < len; ++i) {
                    wstring id=tables[4][0]->getRowColData(selectedrows[i], 0);
                    selectidsandposition[i].first=(stoi(id));
                    selectidsandposition[i].second = selectedrows[i];
                }
                processor.deleteFlightLine(selectidsandposition);
                vector<vector<wstring>>newdata1;
                processor.getQueryPointDataReference(newdata1);
                tables[2][0]->setData(newdata1);
                tables[3][0]->deleteRows(selectedrows);
                tables[4][0]->deleteSelectedRows();
                wstring flight_num = to_wstring(processor.FlightLines.size());
                transformOuttextxy(3, 5, L"当前飞行线数量: " + flight_num);
                transformOuttextxy(4, 0, L"当前飞行线数量: " + flight_num);
            need_to_update_table5 = true;
            });
        addButton(4, button4_2);
    }
    //设置按钮 end

    //设置文字 start
    {
        //飞行线数量
        OutTextXY* out4_1 = new OutTextXY(535, 60, L"当前飞行线数量: ", 18);
        out4_1->setSecondPosition(1070, 120, 32);
        addouttextxy(4, out4_1);


        OutTextXY* out4_2 = new OutTextXY(width - 575, 375, L"tips:点击想要删除的飞行线后，点删除按钮，即可删除", 18);
        addouttextxy(4, out4_2);
    }
    //设置文字 end

    //设置表格 start
    {
        //删除 飞行线界面
        TableWidget* table4_1 = new TableWidget(40, 40, 450, 330, 12, true, 0.5);
        addTable(4, table4_1);
    }
    //设置表格 end
}
//绘制图像界面内容   
void Widget::initContentPage5() {
    //设置按钮 start
    Button* button5_1 = new Button(0, height - 45, 124, 45, L"返回上一页", [&]() {
        setCurrentIndex(2);
        });
    addButton(5, button5_1);
    Button* button5_2 = new Button(91, 251, 33, 30, L"搜索", [&]() {
        wstring textbox5_1_content = textBoxs[5][0]->getText();
        if (textbox5_1_content == L"") {
            return;
        }
        if (!isValidNumber(textbox5_1_content)) {
            MessageBox(GetHWnd(), L"请输入正确的飞行线序号!", L"警告", MB_ICONWARNING | MB_OK);
            textBoxs[5][0]->clear();
        }
        else {
            int lineID = stoi(textbox5_1_content);
            if (!plotView.fitToLine(lineID)) {
                MessageBox(GetHWnd(), L"没有该序号的飞行线!", L"警告", MB_ICONWARNING | MB_OK);
            }
        }
        //plotView.ChangeLineShow(lineID);

        });
    addButton(5, button5_2);
    Button* button5_3 = new Button(0 * 0.5, 281, 124, 30, L"显示/隐藏该飞行线", [&]() {
        wstring textbox5_1_content = textBoxs[5][0]->getText();
        if (textbox5_1_content == L"") {
            return;
        }
        if (!isValidNumber(textbox5_1_content)) {
            MessageBox(GetHWnd(), L"请输入正确的飞行线序号!", L"警告", MB_ICONWARNING | MB_OK);
            textBoxs[5][0]->clear();
        }
        else {
            int lineID = stoi(textbox5_1_content);
            if (!plotView.changeLineShow(lineID)) {
                MessageBox(GetHWnd(), L"没有该序号的飞行线!", L"警告", MB_ICONWARNING | MB_OK);
            }
        }
        //plotView.ChangeLine_Show(lineID);
        });
    addButton(5, button5_3);
    //设置按钮 end

    //设置文字 start
    if (width == screenWidth * 2) {
        OutTextXY* out5_1 = new OutTextXY(2, 315, L"操作说明:", 12, L"宋体", RGB(64, 64, 64));
        addouttextxy(5, out5_1);
        OutTextXY* out5_2 = new OutTextXY(2, 325, L"- 鼠标滚轮缩放图表", 12, L"宋体", RGB(64, 64, 64));
        addouttextxy(5, out5_2);
        OutTextXY* out5_3 = new OutTextXY(2, 335, L"- 左键拖动平移:", 12, L"宋体", RGB(64, 64, 64));
        addouttextxy(5, out5_3);
        OutTextXY* out5_4 = new OutTextXY(2, 345, L"- 点击查询点可到达对应的位置:", 12, L"宋体", RGB(64, 64, 64));
        addouttextxy(5, out5_4);
        OutTextXY* out5_5 = new OutTextXY(2, 355, L"  并显示其到达最近飞行线的距离", 12, L"宋体", RGB(64, 64, 64));
        addouttextxy(5, out5_5);
        OutTextXY* out5_6 = new OutTextXY(2, 365, L"- 再次点击将取消距离的显示", 12, L"宋体", RGB(64, 64, 64));
        addouttextxy(5, out5_6);
    }

    //设置文字 end

    TextBox* textbox5_1 = new TextBox(0, 251, 124, 30, 4);
    textbox5_1->setDefaultText(L"输入飞行线序号", 12);
    textbox5_1->setSecondDefaultText(26);
    textbox5_1->setNextField(textbox5_1);
    textbox5_1->setFinalCallback([button5_2]() {
        button5_2->useOnClick();
        });
    addTextBox(5, textbox5_1);

    //设置表格 start
        //绘制图形
    TableWidget* table5_1 = new TableWidget(0 * 0.5, 0 * 0.5, 114, 250, 10, true, 0.5, 26, 24);
    addTable(5, table5_1);

    //设置表格 end

    //设置地图  start
    plotView = PlotView(248 * rpx,  // 左侧面板宽度
        width,   // 屏幕宽度
        height);   // 屏幕高度

    //设置地图  end

}
//不用文件，直接输入界面输入飞行线内容
void Widget::initContentPage6() {
    //设置按钮 start
    Button* button6_1 = new Button(width - 65, 0, 65, 35, L"返回上一页", [&]() {
        setCurrentIndex(1);
        });
    addButton(6, button6_1);

    Button* button6_2 = new Button(590, 245, 65, 33, L"添加", [&]() {
        wstring inputs[4] = {
            textBoxs[6][0]->getText(),
            textBoxs[6][1]->getText(),
            textBoxs[6][2]->getText(),
            textBoxs[6][3]->getText()
        };
        if (!inputs[0].empty() && !inputs[1].empty() && !inputs[2].empty() && !inputs[3].empty()) {
            // 输入验证
            double coords[4]; bool flag_isNonNegative = true;
            for (int i = 0; i < 4; ++i) {
                // 预处理：移除空格
                inputs[i].erase(std::remove(inputs[i].begin(), inputs[i].end(), ' '), inputs[i].end());
                //// 严格数字验证
                //bool isNumeric = std::all_of(inputs[i].begin(), inputs[i].end(),
                //    [](wchar_t c) { return iswdigit(c); });
                //if (!isNumeric) {
                if (!isValidNumber2(inputs[i])) {
                    flag_isNonNegative = false;
                    textBoxs[6][i]->clear();
                    continue;
                }

                // 转换数字
                coords[i] = std::stod(inputs[i]);
            }
            if (!flag_isNonNegative) {
                MessageBox(GetHWnd(), L"错误：输入数据存在错误信息", L"输入错误", MB_ICONERROR);
            }
            else {
                vector<wstring>arow(2);
                arow[0] = L"(" + formatCoord(coords[0]) + L"," + formatCoord(coords[1]) + L")";
                arow[1] = L"(" + formatCoord(coords[2]) + L"," + formatCoord(coords[3]) + L")";
                processor.DirectlyInputFlightLines.push_back({ -1, coords[0], coords[1], coords[2], coords[3] });   //id暂不处理

                tables[6][0]->addRow(arow);

                textBoxs[6][0]->clear();
                textBoxs[6][1]->clear();
                textBoxs[6][2]->clear();
                textBoxs[6][3]->clear();
                need_to_update_table5 = true;
            }
        }

        });
    addButton(6, button6_2);

    Button* button6_3 = new Button(590, 290, 65, 33, L"删除", [&]() {
        vector<int>selectedrows;
        tables[6][0]->getSelectedRows(selectedrows);
        sort(selectedrows.begin(), selectedrows.end(), greater<int>());

        for (int row : selectedrows) {
            --row;
            if (row >= 0 && row < processor.DirectlyInputFlightLines.size()) {
                processor.DirectlyInputFlightLines.erase(processor.DirectlyInputFlightLines.begin() + row);
            }
        }
        need_to_update_table5 = true;
        tables[6][0]->deleteSelectedRows();
        });
    addButton(6, button6_3);

    Button* button6_4 = new Button(590, 335, 65, 33, L"下一步", [&]() {
        setCurrentIndex(7);
        });
    addButton(6, button6_4);
    //设置按钮 end

    //设置文字 start
    //端点1 x坐标
    OutTextXY* out6_1 = new OutTextXY(535, 113, L"端点1  x坐标 :", 18);
    out6_1->setSecondPosition(1070, 226, 28);
    addouttextxy(6, out6_1);
    //端点1 y坐标
    OutTextXY* out6_2 = new OutTextXY(535, 143, L"端点1  y坐标 :", 18);
    out6_2->setSecondPosition(1070, 286, 28);
    addouttextxy(6, out6_2);
    //端点2 x坐标
    OutTextXY* out6_3 = new OutTextXY(535, 173, L"端点2  x坐标 :", 18);
    out6_3->setSecondPosition(1070, 346, 28);
    addouttextxy(6, out6_3);
    //端点2 y坐标
    OutTextXY* out6_4 = new OutTextXY(535, 203, L"端点2  y坐标 :", 18);
    out6_4->setSecondPosition(1070, 406, 28);
    addouttextxy(6, out6_4);
    //设置文字 end


    //设置文本输入框 start
    {
        TextBox* textbox6_1 = new TextBox(615, 112, 65, 22, 8);//  端点1 X
        TextBox* textbox6_2 = new TextBox(615, 142, 65, 22, 8);//  端点1 Y
        TextBox* textbox6_3 = new TextBox(615, 172, 65, 22, 8);//  端点2 X
        TextBox* textbox6_4 = new TextBox(615, 202, 65, 22, 8);//  端点2 Y
        textbox6_1->setNextField(textbox6_2);
        textbox6_2->setNextField(textbox6_3);
        textbox6_3->setNextField(textbox6_4);
        textbox6_4->setNextField(textbox6_1);
        textbox6_4->setFinalCallback([button6_2]() {
            button6_2->useOnClick();
            });
        addTextBox(6, textbox6_1);
        addTextBox(6, textbox6_2);
        addTextBox(6, textbox6_3);
        addTextBox(6, textbox6_4);
    }
    //设置文本输入框 end

    TableWidget* table6_1 = new TableWidget(40, 40, 450, 330, 12, true, 0.5);
    vector<vector<wstring>>newdata1(1);
    newdata1[0].emplace_back(L"飞行线端点1坐标"); newdata1[0].emplace_back(L"飞行线端点2坐标");
    table6_1->setData(newdata1);
    addTable(6, table6_1);
}
//不用文件，直接输入界面输入查询点内容
void Widget::initContentPage7() {
    //设置按钮 start
    Button* button7_1 = new Button(width - 65, 0, 65, 35, L"返回上一页", [&]() {
        setCurrentIndex(6);
        });
    addButton(7, button7_1);

    Button* button7_2 = new Button(590, 245, 65, 33, L"添加", [&]() {
        wstring inputs[2] = {
            textBoxs[7][0]->getText(),
            textBoxs[7][1]->getText(),
        };
        if (!inputs[0].empty() && !inputs[1].empty()) {
            // 输入验证
            double coords[4]; bool flag_isNonNegative = true;
            for (int i = 0; i < 2; ++i) {
                // 预处理：移除空格
                inputs[i].erase(std::remove(inputs[i].begin(), inputs[i].end(), ' '), inputs[i].end());
                //// 严格数字验证
                //bool isNumeric = std::all_of(inputs[i].begin(), inputs[i].end(),
                //    [](wchar_t c) { return iswdigit(c); });
                //if (!isNumeric) {
                if (!isValidNumber2(inputs[i])) {
                    flag_isNonNegative = false;
                    textBoxs[7][i]->clear();
                    continue;
                }
                // 转换数字

                coords[i] = std::stod(inputs[i]);

            }
            if (!flag_isNonNegative) {
                MessageBox(GetHWnd(), L"错误：输入数据存在错误信息", L"输入错误", MB_ICONERROR);
            }
            else {
                vector<wstring>arow(1);
                arow[0] = L"(" + formatCoord(coords[0]) + L"," + formatCoord(coords[1]) + L")";
                processor.DirectlyInputQueryPoints.push_back({ coords[0], coords[1] });   //id暂不处理
                tables[7][0]->addRow(arow);

                textBoxs[7][0]->clear();
                textBoxs[7][1]->clear();
                need_to_update_table5 = true;
            }
        }

        });
    addButton(7, button7_2);

    Button* button7_3 = new Button(590, 290, 65, 33, L"删除", [&]() {
        vector<int>selectedrows;
        tables[7][0]->getSelectedRows(selectedrows);
        sort(selectedrows.begin(), selectedrows.end(), greater<int>());

        for (int row : selectedrows) {
            --row;
            if (row >= 0 && row < processor.DirectlyInputQueryPoints.size()) {
                processor.DirectlyInputQueryPoints.erase(processor.DirectlyInputQueryPoints.begin() + row);
            }
        }
        need_to_update_table5 = true;
        tables[7][0]->deleteSelectedRows();
        });
    addButton(7, button7_3);

    Button* button7_4 = new Button(590, 335, 65, 33, L"运行", [&]() {
        processor.finishDirectInput();

        vector<vector<wstring>>newdata1;
        processor.getQueryPointDataReference(newdata1);
        tables[2][0]->setData(newdata1);

        vector<vector<wstring>>newdata2;
        processor.getFlightDataReference(newdata2);
        tables[3][0]->setData(newdata2);
        tables[4][0]->setData(newdata2);
        setCurrentIndex(2);
        });
    addButton(7, button7_4);
    //设置按钮 end

    //设置文字 start
    //端点1 x坐标
    OutTextXY* out7_1 = new OutTextXY(535, 140, L"查询点 x坐标 :", 18);
    out7_1->setSecondPosition(1070, 280, 28);
    addouttextxy(7, out7_1);
    //端点1 y坐标
    OutTextXY* out7_2 = new OutTextXY(535, 170, L"查询点 y坐标 :", 18);
    out7_2->setSecondPosition(1070, 340, 28);
    addouttextxy(7, out7_2);
    //设置文字 end


    //设置文本输入框  
    {
        TextBox* textbox7_1 = new TextBox(615, 139, 65, 22, 8);//  端点1 X
        TextBox* textbox7_2 = new TextBox(615, 169, 65, 22, 8);//  端点2 Y
        textbox7_1->setNextField(textbox7_2);
        textbox7_2->setNextField(textbox7_1);
        textbox7_2->setFinalCallback([button7_2]() {
            button7_2->useOnClick();
            });
        addTextBox(7, textbox7_1);
        addTextBox(7, textbox7_2);
    }
    //设置文本输入框 end

    TableWidget* table7_1 = new TableWidget(40, 40, 450, 330, 12, true, 0.5);
    vector<vector<wstring>>newdata1(1);
    newdata1[0].emplace_back(L"查询点坐标");
    table7_1->setData(newdata1);
    addTable(7, table7_1);
}


//设置页面背景
void Widget::initPage() {
    // 创建页面0 
    IMAGE* page0 = new IMAGE(width, height);
    setfillcolor(RGB(240, 240, 240));
    solidrectangle(0, 0, width, height);
    getimage(page0, 0, 0, width, height);
    addPage(page0);

    // 创建页面1    输入样例界面   
    IMAGE* page1 = new IMAGE(width, height);
    setfillcolor(RGB(245, 245, 245));
    solidrectangle(0, 0, width, height);
    getimage(page1, 0, 0, width, height);
    addPage(page1);

    // 创建页面2    运行界面
    IMAGE* page2 = new IMAGE(width, height);
    setfillcolor(RGB(245, 245, 245));
    solidrectangle(0, 0, width, height);
    getimage(page2, 0, 0, width, height);
    addPage(page2);

    // 创建页面3     添加 飞行线界面
    IMAGE* page3 = new IMAGE(width, height);
    setfillcolor(RGB(245, 245, 245));
    solidrectangle(0, 0, width, height);
    getimage(page3, 0, 0, width, height);
    addPage(page3);

    // 创建页面4     删除 飞行线界面
    IMAGE* page4 = new IMAGE(width, height);
    setfillcolor(RGB(245, 245, 245));
    solidrectangle(0, 0, width, height);
    getimage(page4, 0, 0, width, height);
    addPage(page4);

    // 创建页面5    绘制图形界面
    IMAGE* page5 = new IMAGE(width, height);
    setfillcolor(BLACK);  //  setbkcolor(BLACK);
    solidrectangle(248 * rpx, 0, width, height);
    getimage(page5, 0, 0, width, height);
    addPage(page5);

    // 创建页面6    管理员"设置快递柜格口类别个数"界面
    IMAGE* page6 = new IMAGE(width, height);
    setfillcolor(RGB(240, 240, 240));
    solidrectangle(0, 0, width, height);
    getimage(page6, 0, 0, width, height);
    addPage(page6);

    // 创建页面7    管理员"设置快递柜格口类别个数"界面
    IMAGE* page7 = new IMAGE(width, height);
    setfillcolor(RGB(240, 240, 240));
    solidrectangle(0, 0, width, height);
    getimage(page7, 0, 0, width, height);
    addPage(page7);

}
//初始化各个页面的内容
void Widget::initAll() {
    initPage();
    initContentPage0();
    initContentPage1();
    initContentPage2();
    initContentPage3();
    initContentPage4();
    initContentPage5();
    initContentPage6();
    initContentPage7();
    //InitPage8_content();
    //InitPV();
}
//基本的初始化
bool Widget::init()
{
    if (checkAppDatapath(usedatapath)) {
        initgraph(width, height);
        //initgraph(width, height, EX_SHOWCONSOLE);
        //plotView.setDistanceLine(2, 2, 0, 2, 2, 0, 8);
        //plotView.drawDistanceLine();
        //double sum1 = 1.0000, sum2 = 1.000;
        //double dist = std::sqrt(sum1 + sum2);
        //cout << dist << endl;
        //initgraph(width, height, EX_SHOWCONSOLE);
        //LOGFONT f;
        //gettextstyle(&f);
        ////f.lfQuality = PROOF_QUALITY;
        //f.lfQuality = ANTIALIASED_QUALITY;//抗锯齿文字
        ////f.lfQuality = ANTIALIASED_QUALITY| DRAFT_QUALITY;//抗锯齿文字
        //f.lfCharSet = MAC_CHARSET;  //还可以的字符集
        //f.lfWeight = default_Weight;          //指定字符笔画粗细
        ////f.lfClipPrecision = CLIP_EMBEDDED;   //指定文字的剪辑精度
        ////f.lfOutPrecision = OUT_RASTER_PRECIS;
        //settextstyle(&f);

        //初始化内容
        initAll();
        setCurrentIndex(1);
        return true;
    }
    MessageBox(GetHWnd(), L"获取保存应用数据路径失败", L"错误", MB_OK | MB_ICONERROR);
    return false;

}
//界面运行
void Widget::run()
{
    ExMessage msg;
    bool aPressed = false;
    BeginBatchDraw();
    while (true)
    {
        if (peekmessage(&msg))
        {
            int mouseX = msg.x;
            int mouseY = msg.y;
            switch (msg.message)
            {
            case WM_MOUSEMOVE:
                mouseMove(mouseX, mouseY);
                continue;
            case WM_MOUSEWHEEL:
                mouseWheel(mouseX, mouseY, msg.wheel);
                break;
            case WM_LBUTTONDOWN:
                if (aPressed)
                    aPressed = false;
                mouseClick(mouseX, mouseY);
                break;

            case WM_KEYDOWN:
                if (msg.vkcode == VK_CONTROL) {
                    ctrlPressed = true;
                }
                else if (ctrlPressed && msg.vkcode == 'V') {
                    if (currentIndex == 1) {
                        wstring clipboardContent = GetFilePathsFromClipboard();
                        if (!clipboardContent.empty()) {
                            textBoxs[1][0]->setText(clipboardContent);
                            textBoxs[1][0]->backspace = true;
                        }
                        else {
                            clipboardContent = GetClipboardTextW();
                            if (!clipboardContent.empty()) {
                                // 如果获取到普通文本，将其设置到文本框中
                                textBoxs[1][0]->setText(clipboardContent);
                                textBoxs[1][0]->backspace = true;
                            }
                        }
                    }
                }
                break;
            case WM_KEYUP:
                if (msg.vkcode == VK_CONTROL) {
                    ctrlPressed = false;
                }
                break;
            case WM_CHAR:
                keyInput(msg.ch);
                break;
            case WM_LBUTTONUP:
                plotView.ButtonUp(mouseX, mouseY);
                break;
            }
        }
        draw();

        FlushBatchDraw();
        Sleep(10);
    }

    EndBatchDraw();
}
//关闭界面
void Widget::close()
{
    closegraph();
    return;
}


